package com.laolang.shop.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.laolang.shop.common.core.util.AssertUtil;
import com.laolang.shop.common.core.util.SpringUtils;
import com.laolang.shop.modules.sys.consts.entity.SysTenantConst;
import com.laolang.shop.modules.sys.entity.SysTenant;
import com.laolang.shop.modules.sys.mapper.SysTenantMapper;
import com.laolang.shop.modules.sys.service.SysTenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @author khlbat
 * @version 1.0
 * @date 2020/11/1 20:46
 */
@Service
public class SysTenantServiceImpl extends ServiceImpl<SysTenantMapper, SysTenant> implements SysTenantService {

    @Autowired
    private SysTenantMapper sysTenantMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean save(SysTenant entity) {
        entity.setCreateTime(LocalDateTime.now());
        entity.setVersion(1);
        return super.save(entity);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public SysTenant createSysTenant(String code) {
        SysTenantService self = getSelf();

        SysTenant insert = new SysTenant();
        insert.setName(code);
        insert.setCode(code);
        insert.setStatus(SysTenantConst.Status.NORMAL.getValue());
        self.save(insert);
        SysTenant entity = self.getByCode(code);
        AssertUtil.notNull(entity, "添加租户失败");
        return entity;
    }

    @Override
    public SysTenant getByCode(String code) {
        return getOne(Wrappers.<SysTenant>lambdaQuery().eq(SysTenant::getCode, code));
    }

    private SysTenantService getSelf() {
        return SpringUtils.getBean(SysTenantService.class);
    }
}
